import request from 'request';
import Q from 'q';
import cache from 'memory-cache';
import {page_state_cache_key, cache_timeout} from '../constants/global';

export function Get(url) {
    var deferred = Q.defer();
    request.get(url).on('response', function (res) {
        console.log('response->', res);
        deferred.resolve(res);
    }).on('error', function (err) {
        console.log('error->', err);
        deferred.reject(new Error(err));
    });
    return deferred.promise;
}

export function apiGetter(option) {
    var method = option.method;
    var url = option.url;
    var body = option.body;
    var header = option.header;
    var deferred = Q.defer();
    request({
        method: !!method ? method : 'post',
        url: url,
        headers: Object.assign({}, {
            'content-type': 'application/json'
        }, header),
        body: JSON.stringify(body),
        callback: function (err, response, body) {
            //console.log([err, response, body]);
            if (!!err)deferred.reject(err);
            deferred.resolve(body);
        }
    });
    return deferred.promise;
}

export async function getInitState(stateOption) {
    var cacheData = cache.get(page_state_cache_key);
    if (!!cacheData)return cacheData;

    if (!stateOption)return {};
    var defaultProps = !stateOption.props ? {} : stateOption.props;
    var getState = !!stateOption.getState ? stateOption.getState : null;
    if (!!getState) {
        for (var p in getState) {
            var result = await apiGetter(getState[p]);
            if (!!result.Error) {
                return
            }
            defaultProps[p] = result;
            //console.log('post result:->', result)
        }
        cache.put(page_state_cache_key, defaultProps, cache_timeout);
    }
    return defaultProps;
}


